package com.xn.app.muying.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.xn.app.muying.activity.ChanJianListActivity;
import com.xn.app.muying.activity.DengLuActivity;
import com.xn.app.muying.activity.KePuActivity;
import com.xn.app.muying.activity.MainActivity;
import com.xn.app.muying.activity.MessageActivity;
import com.xn.app.muying.activity.MuYingApplication;
import com.xn.app.muying.R;
import com.xn.app.muying.activity.BabyActivity;
import com.xn.app.muying.activity.EducationDetailsActivity;
import com.xn.app.muying.activity.EverydayHearActivity;
import com.xn.app.muying.activity.JiuZhenActivity;
import com.xn.app.muying.activity.RemindActivity;
import com.xn.app.muying.activity.SeekActivity;
import com.xn.app.muying.activity.SheetActivity;
import com.xn.app.muying.activity.VoiceSolutionActivity;
import com.xn.app.muying.activity.VoiceSolutionDetailActivity;
import com.xn.app.muying.activity.WebActivity;
import com.xn.app.muying.activity.YunQiXuanZeActivity;
import com.xn.app.muying.adpter.HomeAdpter;
import com.xn.app.muying.bean.HomeTopBean;
import com.xn.app.muying.bean.ToDayBean;
import com.xn.app.muying.bean.VoiceBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AddPermissions;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.StringUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.util.UpdateManager;
import com.xn.app.muying.view.AutoTextView;
import com.xn.app.muying.view.MarqueeText;
import com.xn.app.muying.view.MyListView;
import com.xn.app.muying.view.RoundImageView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Random;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 首页
 * Created by Administrator on 2016/10/10.
 */
public class HomeFragment extends Fragment implements HttpUtil.OnGetDataListener, View.OnClickListener, View.OnTouchListener, AdapterView.OnItemClickListener, MyListView.IXListViewListener {
    private Handler handler = new Handler();
    private Banner banner = null;
    private ImageView banner_image = null;
    private AutoTextView message_tv = null;
    private LinearLayout yunqishezhi_ll = null;
    public static TextView yunqishezhi_tv = null;
    private String nextAntenatalCareId = "";
    private HomeAdpter homeAdapter = null;
    private MarqueeText top_textview = null;
    private LinearLayout message_ll = null;
    //报告识别
    private RelativeLayout recognition_layout = null;
    //检查科普
    private RelativeLayout science_layout = null;
    //保存孕期状态
    String pregnancyStatus = null;
    //标题栏
    private RelativeLayout home_top_relativelayout = null;
    //标题切换孕期状态按钮
    private RoundImageView type_imageview = null;
    //搜索按钮
    private RoundImageView seek_imageview = null;
    //搜索框
    private LinearLayout seek_textview = null;
    //孕周显示
    private TextView weeks_textview = null;
    //顶部孕周显示
    private TextView home_top_week = null;
    //顶部孕周显示
    private TextView home_top_week_day = null;
    //顶部孕周显示
    private TextView home_top_week_week1 = null;
    //宝宝图片背景
    private ImageView baby_bj = null;
    //填写产检提醒
    private LinearLayout edit_layout = null;
    //显示填写的产检提醒
    private TextView edit_textview = null;
    //宝宝出生距离
    private TextView birthday = null;
    //宝宝体重和身高
    private TextView baby_height_weight = null;
    //问答系统
    private RelativeLayout problem_layout = null;
    //获取今日知识数据
    private ArrayList<ToDayBean> today_list = new ArrayList<>();
    private MyListView listView = null;
    //消息
    private LinearLayout home_top_notice = null;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 5;
    //宝宝生日
    private String babyBirthday = null;
    //预产期
    private String preDeliveryDate = null;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //数据库
    private DBManager db = null;
    //获取用户姓名
    private String userName = null;
    //记录搜索框是否展开
    private boolean seekLean = true;
    //保存banner数据
    private ArrayList<HomeTopBean> bannerArrayList = new ArrayList<>();
    //记录listview滑动距离
    private int selectY = -1;
    //控制标题栏渐变高度   heightY为倍率
    private double heightY = 2;
    //标题栏点击次数
    private long mExitTime;
    //记录当前listview滑动到第几个
    private int listviewPosition = 0;
    /**
     * 语音解答
     */
    //布局
    private LinearLayout voice_linearlayout = null;
    //问题
    private TextView home_interlocution_title = null;
    //医生姓名
    private TextView home_doctor_name = null;
    //医生医院
    private TextView home_doctor_hospitalname = null;
    //医生职称
    private TextView home_doctor_professionaltitle = null;
    //语音时长
    private TextView home_interlocution_time = null;
    //医生头像
    private RoundImageView home_interlocution_img = null;
    //语音播放按钮
    private ImageView home_interlocution_voice = null;
    //查看更多
    private TextView voice_show = null;
    //保存语音数据集合
    private ArrayList<VoiceBean> voiceSolutionList = null;
    //判断是否可以听语音
    private int answerTimes = 0;
    //记录点击时的x轴坐标
    private float mPosX;
    //记录点击时的y轴坐标
    private float mPosY;
    //记录当前的x轴坐标
    private float mCurPosX;
    //记录当前的y轴坐标
    private float mCurPosY;
    //记录屏幕移动位置
    private int ScrollY;
    //记录产检模块布局
    private LinearLayout item_root;
    //记录是否滑动
    private int OnTouchScrollY = -1;
    //产检提醒布局
    private LinearLayout remind_linearlayout = null;
    private ImageView baby_img;
    AlertDialog mydialog;
    //产检提醒时间
    private String remindTime = "";
    //产检时间
    private String antenatalCareTime = "";
    //产检提醒备注
    private String remark = "";
    //保存已经选择的页数
    private ArrayList<Integer> today_array = new ArrayList<>();

    /**
     * 用来接收更新数据
     *
     * @param i
     */
    public void HomeFragment(int i) {
        //i=0  获取数据    i=1 取消数据
        if (i == 0) {
            userName = db.select("tel");
            if (userName != null && !userName.equals("") && !userName.equals("null")) {
                //设置首页的消息提醒
                getMessage();
                //下载viewpager数据
                if (bannerArrayList != null && bannerArrayList.size() <= 0) {
                    HttpUtil.getData(APIMethod.Home_Top, handler, this);
                }
                //下载今日知识数据
                if (today_list != null && today_list.size() <= 0) {
                    //下载今日知识数据
                    getListData();
                }
            }
        } else if (i == 2) {
            //banner启动
            banner.startAutoPlay();
        } else if (i == 3) {
            //banner暂停
            banner.stopAutoPlay();
        } else {
            userName = db.select("tel");
            if (message_ll.getVisibility() == View.VISIBLE) {
                message_ll.setVisibility(View.GONE);
            }
            type_imageview.setImageResource(R.mipmap.home_icon_1);
            top_textview.setText("蓓儿母婴");
            if (remind_linearlayout.getVisibility() == View.VISIBLE) {
                remind_linearlayout.setVisibility(View.GONE);
            }
            if (item_root.getVisibility() == View.VISIBLE) {
                item_root.setVisibility(View.GONE);
            }

            if (banner.getVisibility() == View.GONE) {
                banner.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home_fragment, container, false);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化数据库
        db = new DBManager(getContext());
        //加载并缓存图片
        imageLoader = MyImageLoader.getImageLoader(getActivity());
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.load_failed) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.load_failed) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        //初始化组件
        listView = (MyListView) view.findViewById(R.id.home_fragment_floor);
        top_textview = (MarqueeText) view.findViewById(R.id.home_top_title);
        type_imageview = (RoundImageView) view.findViewById(R.id.home_top_left_img);
        seek_imageview = (RoundImageView) view.findViewById(R.id.home_top_left_seek_img);
        seek_textview = (LinearLayout) view.findViewById(R.id.home_top_left_seek_txt);
        home_top_notice = (LinearLayout) view.findViewById(R.id.home_top_notice);
        home_top_relativelayout = (RelativeLayout) view.findViewById(R.id.home_top_relativelayout);
        //顶部布局组件
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.home_fragment_floor_one, null);
        problem_layout = (RelativeLayout) inflate.findViewById(R.id.problem_layout);
        remind_linearlayout = (LinearLayout) inflate.findViewById(R.id.remind_linearlayout);
        weeks_textview = (TextView) inflate.findViewById(R.id.weeks_textview);
        edit_layout = (LinearLayout) inflate.findViewById(R.id.edit_layout);
        edit_textview = (TextView) inflate.findViewById(R.id.edit_textview);
        home_top_week = (TextView) inflate.findViewById(R.id.home_top_week);
        home_top_week_day = (TextView) inflate.findViewById(R.id.home_top_week_day);
        home_top_week_week1 = (TextView) inflate.findViewById(R.id.home_top_week_week1);
        item_root = (LinearLayout) inflate.findViewById(R.id.item_root);
        birthday = (TextView) inflate.findViewById(R.id.birthday);
        baby_img = (ImageView) inflate.findViewById(R.id.baby_img);
        baby_height_weight = (TextView) inflate.findViewById(R.id.baby_height_weight);
        baby_bj = (ImageView) inflate.findViewById(R.id.baby_bj);
        banner = (Banner) inflate.findViewById(R.id.home_fragment_floor_one_vp);
        banner_image = (ImageView) inflate.findViewById(R.id.banner_image);
        recognition_layout = (RelativeLayout) inflate.findViewById(R.id.recognition_layout);
        science_layout = (RelativeLayout) inflate.findViewById(R.id.science_layout);
        message_ll = (LinearLayout) inflate.findViewById(R.id.home_fragment_message);
        message_tv = (AutoTextView) inflate.findViewById(R.id.home_xiaoxi_tv);
        yunqishezhi_ll = (LinearLayout) inflate.findViewById(R.id.home_yunqishezhi_ll);
        yunqishezhi_tv = (TextView) inflate.findViewById(R.id.home_yunqishezhi_tv);
        home_interlocution_title = (TextView) inflate.findViewById(R.id.home_interlocution_title);
        home_doctor_name = (TextView) inflate.findViewById(R.id.home_doctor_name);
        home_doctor_hospitalname = (TextView) inflate.findViewById(R.id.home_doctor_hospitalname);
        home_doctor_professionaltitle = (TextView) inflate.findViewById(R.id.home_doctor_professionaltitle);
        home_interlocution_time = (TextView) inflate.findViewById(R.id.home_interlocution_time);
        voice_show = (TextView) inflate.findViewById(R.id.voice_show);
        home_interlocution_img = (RoundImageView) inflate.findViewById(R.id.home_interlocution_img);
        home_interlocution_voice = (ImageView) inflate.findViewById(R.id.home_interlocution_voice);
        voice_linearlayout = (LinearLayout) inflate.findViewById(R.id.voice_linearlayout);
        View banner_view = (View) inflate.findViewById(R.id.banner_view);
        RelativeLayout everyday_hear_relativelayout = (RelativeLayout) inflate.findViewById(R.id.everyday_hear_relativelayout);
        //添加listview的头部视图
        listView.addHeaderView(inflate);
        //listView添加适配器
        homeAdapter = new HomeAdpter(getActivity(), imageLoader, options);
        listView.setAdapter(homeAdapter);
        //添加点击事件
        listView.setOnTouchListener(this);
        recognition_layout.setOnTouchListener(this);
        banner_view.setOnTouchListener(this);
        message_ll.setOnTouchListener(this);
        science_layout.setOnTouchListener(this);
        problem_layout.setOnTouchListener(this);
        edit_layout.setOnTouchListener(this);
        seek_textview.setOnClickListener(this);
        seek_imageview.setOnClickListener(this);
        yunqishezhi_ll.setOnClickListener(this);
        message_tv.setOnClickListener(this);
        type_imageview.setOnClickListener(this);
        home_top_notice.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        top_textview.setOnClickListener(this);
        problem_layout.setOnClickListener(this);
        edit_layout.setOnClickListener(this);
        recognition_layout.setOnClickListener(this);
        science_layout.setOnClickListener(this);
        voice_show.setOnClickListener(this);
        home_interlocution_voice.setOnClickListener(this);
        everyday_hear_relativelayout.setOnClickListener(this);
        //初始化轮播控件
        initBanner();
        //设置宝宝背景
        setBabyImg();
        //获取登录信息
        userName = db.select("tel");
        //显示缓存数据
        cache();
        //判断网络状态
        if (NetworkUtil.isNetworkAvailable(getActivity())) {
            today_list = new ArrayList<>();
            //下载viewpager数据
            HttpUtil.getData(APIMethod.Home_Top, handler, this);

            //下载今日知识数据
            getListData();
            //获取版本更新
            new UpdateManager(getContext(), getActivity()).checkUpdate();
            //下载首页语音解答
            getVoiceSolution();
            //如果登陆就下载数据
            if (userName != null && !userName.equals("") && !userName.equals("null")) {
                //设置首页的消息提醒
                getMessage();
            }
        } else {
            banner_image.setImageResource(R.mipmap.bj);
            ToastUtil.showToast(getActivity(), R.string.no_network_hint);
        }
        //listview滚动设置
        setListScroll();
        //注册权限
        AddPermissions.openPermissions(getActivity(), getContext());
    }

    /**
     * 设置宝宝图片动画
     */
    private void setBabyImg() {
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.baby_bj_scale);
        baby_bj.startAnimation(animation);
    }

    /**
     * listview 滚动设置
     */
    private void setListScroll() {
        //判断页面滚动，调整头部搜索栏动画
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            private SparseArray recordSp = new SparseArray(0);
            private int mCurrentfirstVisibleItem = 0;

            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                //关闭搜索栏
                if (!seekLean) {
                    seekLean = true;
                    seek_textview.clearAnimation();
                    Animation testAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 1.0f);
                    testAnimation.setFillAfter(true);
                    testAnimation.setDuration(200);
                    seek_textview.startAnimation(testAnimation);
                    testAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            seek_textview.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            top_textview.setVisibility(TextView.VISIBLE);
                            seek_imageview.setVisibility(TextView.VISIBLE);
                            seek_textview.clearAnimation();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(200);
                                loginHandler.sendEmptyMessage(3);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }

            //listview滚动
            //定义一个变量
            int colorH = 0;

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mCurrentfirstVisibleItem = firstVisibleItem;
                listviewPosition = firstVisibleItem;
                View firstView = view.getChildAt(0);
                if (null != firstView) {
                    ItemRecod itemRecord = (ItemRecod) recordSp.get(firstVisibleItem);
                    if (null == itemRecord) {
                        itemRecord = new ItemRecod();
                    }
                    itemRecord.height = firstView.getHeight();
                    itemRecord.top = firstView.getTop();
                    recordSp.append(firstVisibleItem, itemRecord);
                    ScrollY = getScrollY();
                    if (ScrollY != -1) {
                        int h = (int) (ScrollY / heightY);//滚动距离
                        if (h != selectY) {
                            selectY = h;
                            setTopLayout(0);
                            if (h <= 255) {
                                colorH = 0;
                                home_top_relativelayout.setBackgroundColor(Color.argb(h, 255, 102, 102));
                                top_textview.setTextColor(Color.argb(h, 255, 255, 255));
                            } else {
                                if (colorH == 0) {
                                    colorH++;
                                    home_top_relativelayout.setBackgroundColor(Color.argb(255, 255, 102, 102));
                                    top_textview.setTextColor(Color.argb(255, 255, 255, 255));
                                }

                            }
                        }
                    }

                }
            }

            //获取当前高度
            private int getScrollY() {
                int height = 0;
                try {

                    for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
                        ItemRecod itemRecod = (ItemRecod) recordSp.get(i);
                        height += itemRecod.height;
                    }
                    ItemRecod itemRecod = (ItemRecod) recordSp.get(mCurrentfirstVisibleItem);
                    if (null == itemRecod) {
                        itemRecod = new ItemRecod();
                    }
                    return height - itemRecod.top;
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
            }

            //业务类
            class ItemRecod {
                int height = 0;
                int top = 0;
            }
        });
    }

    /**
     * 点击屏幕滑动监听
     *
     * @param v
     * @param event
     * @return
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosX = event.getX();
                mPosY = event.getY();
                OnTouchScrollY = ScrollY;
                mCurPosX = 0;
                mCurPosY = 0;
                break;
            case MotionEvent.ACTION_MOVE:
                mCurPosX = event.getX();
                mCurPosY = event.getY();
                if (mCurPosY - mPosY < 0
                        && (Math.abs(mCurPosY - mPosY) > 25)) {
                    //向上滑动中
                    if (OnTouchScrollY != -1) {
                        OnTouchScrollY = -1;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:

                if (mCurPosY - mPosY > 0
                        && (Math.abs(mCurPosY - mPosY) > 100)) {
                    //向下滑動后
                    if (OnTouchScrollY == 0 && ScrollY == 0) {
                        setTopLayout(1);
                    }
                } else if (mCurPosY - mPosY < 0
                        && (Math.abs(mCurPosY - mPosY) > 25)) {
                    //向上滑动后
                }
                break;
        }
        return false;
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        final Intent intent = new Intent();
        userName = db.select("tel");
        switch (v.getId()) {
            //标题栏点击使列表滑动到顶部
            case R.id.home_top_title:
                //如果是双击
                if ((System.currentTimeMillis() - mExitTime) > 1000) {
                    mExitTime = System.currentTimeMillis();
                } else {
                    if (listviewPosition > 2) {
                        listView.setSelection(5);
                    }
                    listView.smoothScrollToPosition(0);
                }
                break;
            //通知消息
            case R.id.home_top_notice:
//                if (userName != null && !userName.equals("") && !userName.equals("null")) {
//                    intent.putExtra("SIGN", "return");
//                    intent.setClass(MainActivity.mActivity, JiuZhenActivity.class);
//                    startActivity(intent);
//                } else {
//                    //如果没有登陆，调整到登陆页面
//                    startActivity(new Intent(MainActivity.mActivity, DengLuActivity.class));
//                }
                startActivity(new Intent(MainActivity.mActivity, MessageActivity.class));
                break;
            //搜索按钮
            case R.id.home_top_left_seek_img:
                seekLean = false;
                top_textview.setVisibility(TextView.GONE);
                seek_imageview.setVisibility(TextView.GONE);
                Animation testAnimation = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f);
                testAnimation.setFillAfter(true);
                testAnimation.setDuration(200);
                seek_textview.startAnimation(testAnimation);
                seek_textview.setVisibility(TextView.VISIBLE);
                break;
            //搜索内容
            case R.id.home_top_left_seek_txt:
                startActivity(new Intent(MainActivity.mActivity, SeekActivity.class));
                break;
            //标题栏切换孕期状态
            case R.id.home_top_left_img:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent.putExtra("PAGE_INTENT", "HomeFragment");
                    intent.setClass(getActivity(), YunQiXuanZeActivity.class);
                    startActivity(intent);
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(MainActivity.mActivity, DengLuActivity.class));
                }
                break;
            //设置预产期
            case R.id.home_yunqishezhi_ll:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent.putExtra("PAGE_INTENT", "HomeFragment");
                    intent.setClass(getActivity(), YunQiXuanZeActivity.class);
                    startActivity(intent);
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(MainActivity.mActivity, DengLuActivity.class));
                }
                break;
            //孕产提醒,进入孕前检查
            case R.id.home_xiaoxi_tv:
                //判断退出或者登陆
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent.setClass(getActivity(), KePuActivity.class);
                    startActivity(intent);
                }
                break;
            //每日免费听
            case R.id.everyday_hear_relativelayout:
                startActivity(new Intent(MainActivity.mActivity, EverydayHearActivity.class));
                break;
            //报告识别
            case R.id.recognition_layout:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent.setClass(getActivity(), SheetActivity.class);
                    startActivity(intent);
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(MainActivity.mActivity, DengLuActivity.class));
                }
                break;
            //孕期检查
            case R.id.science_layout:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent.setClass(getActivity(), ChanJianListActivity.class);
                    startActivity(intent);
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(getActivity(), DengLuActivity.class));
                }
                break;
            //语音播放按钮
            case R.id.home_interlocution_voice:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    answerTimes = AppConstant.getAnswerTimes(getActivity());
                    if (answerTimes > 0) {
                        intent.setClass(getActivity(), VoiceSolutionDetailActivity.class);
                        intent.putExtra("id", voiceSolutionList.get(0).getId());
                        startActivity(intent);
                    } else {
                        home_interlocution_voice.setBackgroundResource(R.mipmap.voice_no_moren);
                        ToastUtil.showToast(getActivity(), R.string.no_voice);
                    }
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(getActivity(), DengLuActivity.class));
                }
                break;
            //语音解答查看更多
            case R.id.voice_show:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    intent.setClass(getActivity(), VoiceSolutionActivity.class);
                    startActivity(intent);
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(getActivity(), DengLuActivity.class));
                }
                break;
            //填写产检提醒按钮
            case R.id.edit_layout:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    if (DateUtils.getStringToDate(remindTime.replace("T", " ")) < DateUtils.getNumberDate()) {
                        AppConstant.remindId = "";
                        weeks_textview.setText("");
                        edit_textview.setText("");
                    }
                    intent.setClass(getActivity(), RemindActivity.class);
                    intent.putExtra("id", AppConstant.remindId);
                    intent.putExtra("remark", remark);
                    intent.putExtra("antenatalCareTime", antenatalCareTime);
                    intent.putExtra("remindTime", remindTime);
                    startActivity(intent);
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(getActivity(), DengLuActivity.class));
                }
                break;
            //问答功能
            case R.id.problem_layout:
                if (userName != null && !userName.equals("") && !userName.equals("null")) {
                    //加载框
                    mydialog = new MyAlertDialog().ShowDialog(getActivity(), R.layout.dialog_loading);
                    mydialog.setCancelable(true);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Request request = new Request.Builder().url(APIMethod.WenDa(db.select("id"))).build();
                                okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                                int code = response.code();
                                final String bodys = response.body().string().replace("\"", "");
                                if (code == 200 || code == 204) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (mydialog != null) {
                                                mydialog.dismiss();
                                            }
                                            startActivity(new Intent(getActivity(), WebActivity.class).putExtra("title", "在线问答")
                                                    .putExtra("url", bodys));
                                        }
                                    });
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else {
                    //如果没有登陆，调整到登陆页面
                    startActivity(new Intent(getActivity(), DengLuActivity.class));
                }
                break;
        }
    }

    /**
     * 设置顶部布局
     *
     * @param i 1代表打开   0代表关闭
     */
    private void setTopLayout(int i) {
        if (pregnancyStatus != null && pregnancyStatus.equals("1") && StringUtil.judgeNull(userName)) {
            //处于怀孕期，才显示
            if (i == 1) {
                if (item_root.getVisibility() == View.GONE) {
//                    if (item_root.getAnimation() != null) {
//                        item_root.clearAnimation();
//                    }
                    //拉出布局
                    Animation scaleAnimation = new ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f);
                    scaleAnimation.setFillAfter(true);
                    scaleAnimation.setDuration(500);
                    item_root.startAnimation(scaleAnimation);
                    item_root.setVisibility(View.VISIBLE);
                    scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            if (banner.getVisibility() == View.VISIBLE) {
                                banner.setVisibility(View.GONE);
                            }
                            item_root.clearAnimation();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                }
            } else {
                if (item_root.getVisibility() == View.VISIBLE) {
                    //收起布局
                    Animation scaleAnimation = new ScaleAnimation(1.0f, 1.0f, 1.0f, 0.0f);
                    scaleAnimation.setFillAfter(true);
                    scaleAnimation.setDuration(500);
                    item_root.startAnimation(scaleAnimation);
                    item_root.setVisibility(View.GONE);
                    scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            if (banner.getVisibility() == View.GONE) {
                                banner.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            item_root.clearAnimation();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                }
            }
        }
    }

    //初始化Banner
    private void initBanner() {
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Accordion);
        banner.isAutoPlay(true);
        banner.setDelayTime(3000);
        banner.setImageLoader(new com.youth.banner.loader.ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                HomeTopBean homeTopBean = (HomeTopBean) path;
                imageLoader.displayImage(homeTopBean.getPictureUrl(), imageView, options, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {
                        //开始加载的时候执行
                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {
                        //加载失败的时候执行
                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        //加载成功的时候执行
                        banner.setVisibility(Banner.VISIBLE);
                        banner_image.setVisibility(ImageView.GONE);
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {
                        //加载取消的时候执行
                    }
                });
            }
        });
        //点击事件
        banner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                if (bannerArrayList.size() > 0 && position > 0) {
                    startActivity(new Intent(getActivity(), EducationDetailsActivity.class)
                            .putExtra("id", bannerArrayList.get(position - 1).getLinkUrl())
                            .putExtra("type", 1)
                            .putExtra("name", bannerArrayList.get(position - 1).getTitle())
                            .putExtra("title", "1")
                            .putExtra("content", bannerArrayList.get(position - 1).getDescription())
                            .putExtra("pic", bannerArrayList.get(position - 1).getPictureUrl()));
                }
            }
        });
    }

    //加载框
    MyAlertDialog dialogDengLu;

    /**
     * 账号过期重新登录
     */
    private void setDengLu() {
        try {
            //初始化数据
            if (db.selectNull(DBManager.USER_TABLE) != 0) {
                db.delete(DBManager.USER_TABLE);
            }
            if (db.selectNull(DBManager.CACHE_TABLE) != 0) {
                db.delete(DBManager.CACHE_TABLE);
            }
            if (message_ll.getVisibility() == View.VISIBLE) {
                message_ll.setVisibility(LinearLayout.GONE);
            }
            if (remind_linearlayout.getVisibility() == View.VISIBLE) {
                remind_linearlayout.setVisibility(View.GONE);
            }
            if (item_root.getVisibility() == View.VISIBLE) {
                item_root.setVisibility(View.GONE);
            }

            if (banner.getVisibility() == View.GONE) {
                banner.setVisibility(View.VISIBLE);
            }
            type_imageview.setImageResource(R.mipmap.home_icon_1);
            //加载弹出框
            dialogDengLu = new MyAlertDialog();
            dialogDengLu.DengLu_Dialog(getContext(), R.layout.denglu_dialog);
            //设置内容
            TextView data = dialogDengLu.getData();
            //设置取消按钮
            TextView getCancel_text = dialogDengLu.getCancel_text();
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (dialogDengLu != null) {
                        dialogDengLu.dismiss();
                    }
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), DengLuActivity.class);
                    startActivity(intent);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //加载框
    MyAlertDialog dialog;

    /**
     * 判断用户baby是否出生
     */
    private void setBabyInfo() {
        try {
            //加载弹出框
            dialog = new MyAlertDialog();
            dialog.Prompt_Dialog(getContext(), R.layout.prompt_dialog);
            //设置内容
            TextView data = dialog.getData();
            data.setText("亲爱的麻麻，您的宝宝出生了吗？");
            //设置取消按钮
            TextView getCancel_text = dialog.getCancel_text();
            getCancel_text.setText("未出生");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            //设置确认按钮
            TextView getConfirm_text = dialog.getConfirm_text();
            getConfirm_text.setText("出生");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), BabyActivity.class);
                    startActivity(intent);
                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //获取首页消息提醒
    private void getMessage() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.InfoRemind).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 401) {
                        loginHandler.sendEmptyMessage(4);
                    } else if (code == 200 || code == 204) {
                        onJsonInfo(bodys, 0);
                    } else {
                        onJsonInfo(bodys, 1);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //解析首页消息提醒
    private void onJsonInfo(String bodys, int i) {
        try {
            Log.e("bodys=", bodys);
            //获得用户消息
            //放到这里的原因是  用户进入先获取账户是否正确，如果正确在加载用户信息
            getMineInfo();
            if (i == 0) {
                //获取数据正常
                JSONObject jsonObject = new JSONObject(bodys);
                final String tipMessage = jsonObject.optString("tipMessage");
                pregnancyStatus = jsonObject.optString("pregnancyStatus");
                nextAntenatalCareId = jsonObject.optString("nextAntenatalCareId");
                final String antenatalCareRemind = jsonObject.optString("antenatalCareRemind");
                final String pregnancyWeek = jsonObject.optString("pregnancyWeek");
                final String pregnancyWeekDay = jsonObject.optString("pregnancyWeekDay");
                final String birthDay = jsonObject.optString("birthDay");
                final int babyHeight = jsonObject.optInt("babyHeight");
                final int babyWeight = jsonObject.optInt("babyWeight");
                if (StringUtil.judgeNull(antenatalCareRemind)) {
                    jsonObject = new JSONObject(antenatalCareRemind);
                    remindTime = jsonObject.optString("remindTime");
                    antenatalCareTime = jsonObject.optString("antenatalCareTime");
                    remark = jsonObject.optString("remark");
                    AppConstant.remindId = jsonObject.optString("id");
                } else {
                    remindTime = "";
                    antenatalCareTime = "";
                    remark = "";
                    AppConstant.remindId = "";
                }
                if (pregnancyStatus.equals("0")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            yunqishezhi_tv.setText("备孕期^_^");
                            type_imageview.setImageResource(R.mipmap.home_icon_4);
                            message_tv.setText(tipMessage);
                        }
                    });

                } else if (pregnancyStatus.equals("1")) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            yunqishezhi_tv.setText("怀孕期^_^");
                            type_imageview.setImageResource(R.mipmap.home_icon_3);
                            message_tv.setText(tipMessage);
                            if (StringUtil.judgeNull(antenatalCareRemind)) {
                                weeks_textview.setText(remindTime.replace("T", " "));
                                if (StringUtil.judgeNull(remark)) {
                                    edit_textview.setText(remark);
                                } else {
                                    edit_textview.setText("");
                                    edit_textview.setHint("有没有什么需要提醒自己?例如:需要空腹。");
                                }
                            }
                            home_top_week.setText("已怀孕" + pregnancyWeek);
                            home_top_week_day.setText("+" + pregnancyWeekDay);
                            home_top_week_week1.setText("周");
                            birthday.setText("距离宝宝出生还有" + birthDay + "天");
                            if (Integer.parseInt(pregnancyWeek) >= 13 && Integer.parseInt(pregnancyWeek) <= 40) {
                                if (babyHeight == 0) {
                                    baby_height_weight.setText("体重" + babyWeight + "g");
                                } else {
                                    baby_height_weight.setText("身高" + babyHeight + "mm | 体重" + babyWeight + "g");
                                }
                                if (baby_height_weight.getVisibility() == View.GONE) {
                                    baby_height_weight.setVisibility(View.VISIBLE);
                                }
                            } else {
                                if (baby_height_weight.getVisibility() == View.VISIBLE) {
                                    baby_height_weight.setVisibility(View.GONE);
                                }

                            }
                            baby_img.setImageResource(StringUtil.getResource(getContext(), "week_header_" + pregnancyWeek, "mipmap"));
                        }
                    });
                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        type_imageview.setImageResource(R.mipmap.home_icon_5);
                        message_ll.setVisibility(View.GONE);
                    }
                });

            }

            //添加缓存数据
            if (db.selectNull(DBManager.CACHE_TABLE) != 0) {
                db.updateCache(bodys, "prompt");
            } else {
                db.insertCache(bodys, "prompt");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户消息
     */
    private void getMineInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.UserInfo).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    onJsonMine(bodys);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /***
     * 解析用户信息
     * 将baby出生日期转换成x岁x月x天格式
     * 顶部的title显示baby年龄，并且隐藏消息栏
     */

    private void onJsonMine(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            pregnancyStatus = jsonObject.optString("pregnancyStatus");
            preDeliveryDate = jsonObject.optString("preDeliveryDate");
            babyBirthday = jsonObject.optString("babyBirthday");
            int isVIP = 0;
            if (jsonObject.getBoolean("isVIP")) {
                isVIP = 1;
            }
            int isCanTrialVIP = 0;
            if (jsonObject.getBoolean("isCanTrialVIP")) {
                isCanTrialVIP = 1;
            }
            //获取用户id
            String id = jsonObject.optString("id");
            //获取用户openId
            String openId = "";
            //为用户默认绑定医院
            String antenatalCareHospitalId = jsonObject.optString("antenatalCareHospitalId");
            String antenatalCareHospitalName;
            if (antenatalCareHospitalId == null || antenatalCareHospitalId.equals("") || antenatalCareHospitalId.equals("null")) {
                antenatalCareHospitalId = "1";
                antenatalCareHospitalName = "延安大学附属医院";
                updateInterfaceData(antenatalCareHospitalId);
            } else {
                antenatalCareHospitalId = jsonObject.optString("antenatalCareHospitalId");
                antenatalCareHospitalName = jsonObject.optString("antenatalCareHospitalName");
            }
            //添加用户数据
            db.updateUser(id, openId, jsonObject.optString("identityId"), jsonObject.optString("name"), jsonObject.optString("pregnancyStatus"), jsonObject.optString("pregnancyStatusDisplay"), jsonObject.optString("preDeliveryDate"), antenatalCareHospitalId,
                    antenatalCareHospitalName, jsonObject.optString("babyBirthday"), jsonObject.optString("babyGender"), isVIP, isCanTrialVIP, jsonObject.optString("vipEndTime"), userName);
            //测试查询数据（后期删除）
//            db.select1();
            //宝宝出生，计算年龄
            if (pregnancyStatus.equals("2") && babyBirthday != null && !babyBirthday.equals("") && !babyBirthday.equals("null")) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (banner.getVisibility() == View.GONE) {
                            banner.setVisibility(View.VISIBLE);
                        }
                        String[] str = babyBirthday.split("T");
                        try {
                            type_imageview.setImageResource(R.mipmap.home_icon_5);
                            String[] baby = str[0].split("-");
                            Calendar now = Calendar.getInstance();
                            int day = now.get(Calendar.DAY_OF_MONTH) - Integer.parseInt(baby[2]);
                            int month = now.get(Calendar.MONTH) + 1 - Integer.parseInt(baby[1]);
                            int year = now.get(Calendar.YEAR) - Integer.parseInt(baby[0]);
                            //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
                            if (day < 0) {
                                month -= 1;
                                now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
                                day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
                            }
                            if (month < 0) {
                                month = (month + 12) % 12;
                                if (year > 0) {
                                    year--;
                                }
                            }
                            if (year == 0 && month == 0 && day == 0) {
                                top_textview.setText("宝宝诞生日");
                            } else {
                                top_textview.setText(year + "岁" + month + "月" + day + "天");
                            }
                            if (message_ll.getVisibility() == View.VISIBLE) {
                                message_ll.setVisibility(View.GONE);
                            }
                            if (remind_linearlayout.getVisibility() == View.VISIBLE) {
                                remind_linearlayout.setVisibility(View.GONE);
                            }
                            if (item_root.getVisibility() == View.VISIBLE) {
                                item_root.setVisibility(View.GONE);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            //备孕期
            if (pregnancyStatus.equals("0")) {
                loginHandler.sendEmptyMessage(0);

            }
            //怀孕期
            if (pregnancyStatus.equals("1")) {

                if (preDeliveryDate != null && !preDeliveryDate.equals("") && !preDeliveryDate.equals("null")) {
                    loginHandler.sendEmptyMessage(1);
                    String[] str = preDeliveryDate.split("T");
                    //如果预产期时间戳大于等于当前时间，就询问用户宝宝是否出生
                    if (DateUtils.getStringToDate2(str[0]) <= DateUtils.getStringToDate2(DateUtils.getCurrentDate())) {
                        loginHandler.sendEmptyMessage(2);
                    }
                } else {
                    loginHandler.sendEmptyMessage(1);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            String antenatalCareHospitalName = db.select("antenatalCareHospitalName");
            switch (msg.what) {
                //备孕期
                case 0:
                    if (banner.getVisibility() == View.GONE) {
                        banner.setVisibility(View.VISIBLE);
                    }
                    if (message_ll.getVisibility() == View.GONE) {
                        message_ll.setVisibility(View.VISIBLE);
                    }
                    if (remind_linearlayout.getVisibility() == View.VISIBLE) {
                        remind_linearlayout.setVisibility(View.GONE);
                    }
                    if (item_root.getVisibility() == View.VISIBLE) {
                        item_root.setVisibility(View.GONE);
                    }
                    if (antenatalCareHospitalName != null && !antenatalCareHospitalName.equals("") && !antenatalCareHospitalName.equals("null")) {
//                        top_textview.setText(antenatalCareHospitalName.replace(" ", "") + "蓓儿母婴");
                        top_textview.setText("蓓儿母婴");
                    } else {
                        top_textview.setText("蓓儿母婴");
                    }
                    break;
                //怀孕期
                case 1:
                    if (banner.getVisibility() == View.VISIBLE) {
                        banner.setVisibility(View.GONE);
                    }
                    if (item_root.getVisibility() == View.GONE) {
                        item_root.setVisibility(View.VISIBLE);
                    }
                    if (message_ll.getVisibility() == View.VISIBLE) {
                        message_ll.setVisibility(View.GONE);
                    }
                    if (remind_linearlayout.getVisibility() == View.GONE) {
                        remind_linearlayout.setVisibility(View.VISIBLE);
                    }
                    if (antenatalCareHospitalName != null && !antenatalCareHospitalName.equals("") && !antenatalCareHospitalName.equals("null")) {
//                        top_textview.setText(antenatalCareHospitalName.replace(" ", "") + "蓓儿母婴");
                        top_textview.setText("蓓儿母婴");
                    } else {
                        top_textview.setText("蓓儿母婴");
                    }
                    break;
                //宝宝是否出生提醒
                case 2:
                    if (banner.getVisibility() == View.VISIBLE) {
                        banner.setVisibility(View.GONE);
                    }
                    if (item_root.getVisibility() == View.GONE) {
                        item_root.setVisibility(View.VISIBLE);
                    }
                    if (message_ll.getVisibility() == View.VISIBLE) {
                        message_ll.setVisibility(View.GONE);
                    }
                    if (remind_linearlayout.getVisibility() == View.GONE) {
                        remind_linearlayout.setVisibility(View.VISIBLE);
                    }
                    setBabyInfo();
                    break;
                case 3:
                    seek_textview.clearAnimation();
                    seek_textview.setVisibility(TextView.GONE);
                    break;
                //账号过期
                case 4:
                    setDengLu();
                    break;
                //登陆推送
                case 5:
                    //获取数据
                    Bundle bundle = (Bundle) msg.obj;
                    //开启广播
                    //创建一个意图对象
                    Intent intent = new Intent();
                    //指定发送广播的频道
                    intent.setAction(AppConstant.MY_ACTION);
                    //发送文章id
                    intent.putExtra("id", bundle.getString("id"));
                    //发送标题内容
                    intent.putExtra("title", bundle.getString("title"));
                    //发送分类
                    intent.putExtra("name", bundle.getString("name"));
                    //发送显示内容
                    intent.putExtra("data", bundle.getString("shortDescription"));
                    //发送图片
                    intent.putExtra("pictureUrl", bundle.getString("pictureUrl"));
                    //发送
                    getActivity().sendBroadcast(intent);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 解析Banner的viewpager数据
     */
    @Override
    public void onJsonData(String data) {
        try {
            //保存banner信息
            //添加缓存数据
            if (db.selectNull(DBManager.CACHE_TABLE) != 0) {
                db.updateCache(data, "Banner");
            } else {
                db.insertCache(data, "Banner");
            }
            //解析并显示
            JSONArray array = new JSONArray(data);
            bannerArrayList = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String pictureUrl = jsonObject.optString("pictureUrl");
                String id = jsonObject.optString("id");
                String title = jsonObject.optString("title");
                String linkUrl = jsonObject.optString("linkUrl");
                String description = jsonObject.optString("description");
                HomeTopBean homeTopBean = new HomeTopBean();
                homeTopBean.setPictureUrl(pictureUrl);
                homeTopBean.setId(id);
                homeTopBean.setTitle(title);
                homeTopBean.setLinkUrl(linkUrl);
                homeTopBean.setDescription(description);
                bannerArrayList.add(homeTopBean);
            }
            if (bannerArrayList.size() > 0) {
                banner.setImages(bannerArrayList);
                banner.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (today_list.size() != 0 && i != 0) {
            Intent intent = new Intent();
            intent.setClass(getActivity(), EducationDetailsActivity.class);
            intent.putExtra("type", 1);
            intent.putExtra("id", today_list.get(i - 1).getId());//添加头部视图，0被占用，所以索引从1开始
            intent.putExtra("name", today_list.get(i - 1).getName());
            intent.putExtra("title", today_list.get(i - 1).getTitle());
            intent.putExtra("content", today_list.get(i - 1).getShortDescription());
            intent.putExtra("pic", today_list.get(i - 1).getPictureUrl());
            startActivity(intent);
        }
    }

    /**
     * 选择就诊医院
     *
     * @param id
     */
    private void updateInterfaceData(final String id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("antenatalCareHospitalId", id);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.JiuZhenHospital_Sumit).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    if (code == 204 || code == 200) {

                    } else {

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 获取今日知识
     */
    boolean notification = true;
    private void getListData() {
        if (totalCount != 0) {
            int i = (totalCount / number) + 1;
            while (getRandom(i)){

            }
        }
        HttpUtil.getData(APIMethod.Home_ToDay(currentPage, number), handler, new HttpUtil.OnGetDataListener() {
            @Override
            public void onJsonData(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (totalCount == 0) {
                        //保存总页数
                        totalCount = jsonObject.getInt("totalCount");
                    }

                    if (notification) {
                        notification = false;
                        //登陆推送内容id
                        int i = new Random().nextInt(totalCount);
                        //推送内容
                        getNewNotification(i);
                    }

                    JSONArray items = jsonObject.getJSONArray("items");
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject object = items.getJSONObject(i);
                        String title = object.optString("title");
                        String pictureUrl = object.optString("pictureUrl");
                        String shortDescription = object.optString("shortDescription");
                        String id = object.optString("id");
                        JSONObject jsonObject1 = new JSONObject(object.optString("category"));
                        String name = jsonObject1.optString("name");
                        ToDayBean toDayBean = new ToDayBean();
                        toDayBean.setTitle(title);
                        toDayBean.setPictureUrl(pictureUrl);
                        toDayBean.setShortDescription(shortDescription);
                        toDayBean.setId(id);
                        toDayBean.setName(name);
                        today_list.add(toDayBean);
                    }
                    onLoad();
                    listView.setPullLoadEnable(true);
                    if(today_list.size()/number!=0){
                        listView.setXListViewListener(HomeFragment.this, totalCount, today_list.size()/number+1, number);
                    }else{
                        listView.setXListViewListener(HomeFragment.this, totalCount, today_list.size()/number, number);
                    }
                    homeAdapter.getData(today_list);
                    //保存第一次获取到的5条数据
                    if (currentPage == 1) {
                        //添加缓存数据
                        if (db.selectNull(DBManager.CACHE_TABLE) != 0) {
                            db.updateCache(data, "Today_know");
                        } else {
                            db.insertCache(data, "Today_know");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public boolean  getRandom(int i){
       int ranInt= new Random().nextInt(i);
        boolean iLean = false;
        for(Integer integer:today_array){
            if(integer==ranInt){
                iLean=true;
            }
        }

        if(!iLean){
            currentPage=ranInt;
            today_array.add(ranInt);
        }
        return iLean;

    }

    /**
     * 获取首页语音解答
     */
    public void getVoiceSolution() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 113为暂时总数
                    int i = new Random().nextInt(113);

                    Request request = new Request.Builder().url(APIMethod.HomeVoiceSolution(i, 1)).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    int code = response.code();
                    if (code == 200 || code == 204) {
                        onJsonVoiceSolution(bodys);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 首页语音解答数据解析
     *
     * @param bodys 数据
     */
    private void onJsonVoiceSolution(String bodys) {
        try {
            //解析数据
            JSONObject jsonObject = new JSONObject(bodys);
            JSONArray jsonArray = jsonObject.getJSONArray("items");
            voiceSolutionList = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                int id = jsonObject.getInt("id");
                String title = jsonObject.getString("title");
                String lable = jsonObject.getString("lable");
                String author = jsonObject.getString("author");
                int price = jsonObject.getInt("price");
                int frequencyId = jsonObject.getInt("frequencyId");
                String reference = jsonObject.getString("reference");
                boolean isPresent = jsonObject.getBoolean("isPresent");
                String remainingTimes = jsonObject.getString("remainingTimes");
                int doctorId = jsonObject.getInt("doctorId");
                //获取语音信息
                JSONObject jsonObject1 = new JSONObject(jsonObject.getString("frequency"));
                String frequencyName = jsonObject1.getString("frequencyName");
                String frequencyUploadDate = jsonObject1.getString("frequencyUploadDate");
                String frequencyUrl = jsonObject1.getString("frequencyUrl");
                String playDate = jsonObject1.getString("playDate");
                int playTime = jsonObject1.getInt("playTime");
                //获取医生信息
                JSONObject jsonObject2 = new JSONObject(jsonObject.getString("doctor"));
                String name = jsonObject2.getString("name");
                String photoUrl = jsonObject2.getString("photoUrl");
                String professionalTitle = jsonObject2.getString("professionalTitle");
                String primaryDepartmentName = jsonObject2.getString("primaryDepartmentName");
                String primaryHospitalName = jsonObject2.getString("primaryHospitalName");
                String expertise = jsonObject2.getString("expertise");
                String expertise2 = jsonObject2.getString("expertise2");
                String expertise3 = jsonObject2.getString("expertise3");
                String expertiseInput = jsonObject2.getString("expertiseInput");
                boolean isDeleted = jsonObject2.getBoolean("isDeleted");
                String doctorInfoId = jsonObject2.getString("doctorInfoId");
                //封装数据
                VoiceBean voiceBean = new VoiceBean();
                voiceBean.setId(id);
                voiceBean.setTitle(title);
                voiceBean.setLable(lable);
                voiceBean.setAuthor(author);
                voiceBean.setPrice(price);
                voiceBean.setFrequencyId(frequencyId);
                voiceBean.setFrequencyName(frequencyName);
                voiceBean.setFrequencyUploadDate(frequencyUploadDate);
                voiceBean.setFrequencyUrl(frequencyUrl);
                voiceBean.setPlayDate(playDate);
                voiceBean.setPlayTime(playTime);
                voiceBean.setDoctorId(doctorId);
                voiceBean.setName(name);
                voiceBean.setPhotoUrl(photoUrl);
                voiceBean.setProfessionalTitle(professionalTitle);
                voiceBean.setPrimaryDepartmentName(primaryDepartmentName);
                voiceBean.setPrimaryHospitalName(primaryHospitalName);
                voiceBean.setExpertise(expertise);
                voiceBean.setExpertise2(expertise2);
                voiceBean.setExpertise3(expertise3);
                voiceBean.setExpertiseInput(expertiseInput);
                voiceBean.setDeleted(isDeleted);
                voiceBean.setDoctorInfoId(doctorInfoId);
                voiceBean.setReference(reference);
                voiceBean.setPresent(isPresent);
                voiceBean.setRemainingTimes(remainingTimes);
                voiceSolutionList.add(voiceBean);
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    home_interlocution_title.setText(voiceSolutionList.get(0).getTitle());
                    home_doctor_name.setText(voiceSolutionList.get(0).getName());
                    home_doctor_hospitalname.setText(voiceSolutionList.get(0).getPrimaryHospitalName());
                    home_doctor_professionaltitle.setText(voiceSolutionList.get(0).getPrimaryDepartmentName());
                    answerTimes = AppConstant.getAnswerTimes(getActivity());
                    if (answerTimes <= 0) {
                        home_interlocution_voice.setBackgroundResource(R.mipmap.voice_no_moren);
                    }
                    home_interlocution_time.setText(DateUtils.getTime(voiceSolutionList.get(0).getPlayTime() + 5));
                    imageLoader.displayImage(voiceSolutionList.get(0).getPhotoUrl(), home_interlocution_img, options, new ImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String s, View view) {

                        }

                        @Override
                        public void onLoadingFailed(String s, View view, FailReason failReason) {
                            home_interlocution_img.setImageResource(R.mipmap.home_doctor_moren);
                        }

                        @Override
                        public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                        }

                        @Override
                        public void onLoadingCancelled(String s, View view) {

                        }
                    });
                    voice_linearlayout.setVisibility(View.VISIBLE);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //上拉加载
    @Override
    public void onLoadMore() {
        if (NetworkUtil.isNetworkAvailable(getActivity())) {
            if (totalCount >today_list.size()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(AppConstant.THREAD_SLEEP);
                            getListData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else {
                onLoad();
            }
        } else {
            onLoad();
            ToastUtil.showToast(getActivity(), R.string.no_network_hint);
        }

    }


    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listView.stopLoadMore();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * 缓存的数据
     */
    private void cache() {
        try {
            //获取今日知识数据
            String data = db.selectCache("Today_know");
            //显示
            if (data != null && !data.equals("") && !data.equals("null")) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (totalCount == 0) {
                        totalCount = jsonObject.getInt("totalCount");
                    }
                    JSONArray items = jsonObject.getJSONArray("items");
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject object = items.getJSONObject(i);
                        String title = object.optString("title");
                        String pictureUrl = object.optString("pictureUrl");
                        String shortDescription = object.optString("shortDescription");
                        String id = object.optString("id");
                        ToDayBean toDayBean = new ToDayBean();
                        toDayBean.setTitle(title);
                        toDayBean.setPictureUrl(pictureUrl);
                        toDayBean.setShortDescription(shortDescription);
                        toDayBean.setId(id);
                        today_list.add(toDayBean);
                    }
                    listView.setPullLoadEnable(true);
                    listView.setXListViewListener(HomeFragment.this, totalCount, currentPage, number);
                    homeAdapter.getData(today_list);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (userName != null && !userName.equals("") && !userName.equals("null")) {
                //设置孕期
                String data1 = db.selectCache("prompt");
                //显示孕期信息
                if (data1 != null && !data1.equals("") && !data1.equals("null")) {
                    try {
                        JSONObject jsonObject = new JSONObject(data1);
                        String pregnancyStatus = db.select("pregnancyStatus");
                        String tipMessage = jsonObject.optString("tipMessage");
                        if (pregnancyStatus != null) {
                            if (pregnancyStatus.equals("0")) {
                                yunqishezhi_tv.setText("备孕期^_^");
                                message_ll.setVisibility(View.VISIBLE);
                                type_imageview.setImageResource(R.mipmap.home_icon_4);
                            } else if (pregnancyStatus.equals("1")) {
                                seekLean = false;
                                top_textview.setVisibility(TextView.GONE);
                                seek_imageview.setVisibility(TextView.GONE);
                                seek_textview.setVisibility(TextView.VISIBLE);
                                final String pregnancyWeek = jsonObject.optString("pregnancyWeek");
                                final String pregnancyWeekDay = jsonObject.optString("pregnancyWeekDay");
                                final String birthDay = jsonObject.optString("birthDay");
                                final int babyHeight = jsonObject.optInt("babyHeight");
                                final int babyWeight = jsonObject.optInt("babyWeight");
                                final String antenatalCareRemind = jsonObject.optString("antenatalCareRemind");
                                if (StringUtil.judgeNull(antenatalCareRemind)) {
                                    jsonObject = new JSONObject(antenatalCareRemind);
                                    remindTime = jsonObject.optString("remindTime");
                                    AppConstant.remindId = jsonObject.optString("id");
                                    if (DateUtils.getStringToDate(remindTime.replace("T", " ")) < DateUtils.getNumberDate()) {
                                        AppConstant.remindId = "";
                                        weeks_textview.setText("");
                                        edit_textview.setText("");
                                    }
                                    antenatalCareTime = jsonObject.optString("antenatalCareTime");
                                    remark = jsonObject.optString("remark");
                                } else {
                                    remindTime = "";
                                    antenatalCareTime = "";
                                    remark = "";
                                    AppConstant.remindId = "";
                                }
                                if (StringUtil.judgeNull(antenatalCareRemind) && StringUtil.judgeNull(AppConstant.remindId)) {
                                    weeks_textview.setText(remindTime.replace("T", " "));
                                    if (StringUtil.judgeNull(remark)) {
                                        edit_textview.setText(remark);
                                    } else {
                                        edit_textview.setText("");
                                        edit_textview.setHint("有没有什么需要提醒自己?例如:需要空腹。");
                                    }
                                }
                                home_top_week.setText("已怀孕" + pregnancyWeek);
                                home_top_week_day.setText("+" + pregnancyWeekDay);
                                home_top_week_week1.setText("周");
                                birthday.setText("距离宝宝出生还有" + birthDay + "天");
                                if (Integer.parseInt(pregnancyWeek) >= 13 && Integer.parseInt(pregnancyWeek) <= 40) {
                                    if (babyHeight == 0) {
                                        baby_height_weight.setText("体重" + babyWeight + "g");
                                    } else {
                                        baby_height_weight.setText("身高" + babyHeight + "mm | 体重" + babyWeight + "g");
                                    }
                                    if (baby_height_weight.getVisibility() == View.GONE) {
                                        baby_height_weight.setVisibility(View.VISIBLE);
                                    }
                                } else {
                                    if (baby_height_weight.getVisibility() == View.VISIBLE) {
                                        baby_height_weight.setVisibility(View.GONE);
                                    }
                                }
                                baby_img.setImageResource(StringUtil.getResource(getContext(), "week_header_" + pregnancyWeek, "mipmap"));
                                yunqishezhi_tv.setText("怀孕期^_^");
                                type_imageview.setImageResource(R.mipmap.home_icon_3);
                                if (item_root.getVisibility() == View.GONE) {
                                    item_root.setVisibility(View.VISIBLE);
                                }
                                if (banner.getVisibility() == View.VISIBLE) {
                                    banner.setVisibility(View.GONE);
                                }
                                if (message_ll.getVisibility() == View.VISIBLE) {
                                    message_ll.setVisibility(View.GONE);
                                }
                                if (remind_linearlayout.getVisibility() == View.GONE) {
                                    remind_linearlayout.setVisibility(View.VISIBLE);
                                }
                            } else if (pregnancyStatus.equals("") || pregnancyStatus.equals("null")) {
                                type_imageview.setImageResource(R.mipmap.home_icon_1);
                            } else {
                                type_imageview.setImageResource(R.mipmap.home_icon_5);
                            }
                        } else {
                            type_imageview.setImageResource(R.mipmap.home_icon_1);
                        }
                        message_tv.setText(tipMessage);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                message_ll.setVisibility(LinearLayout.GONE);
                if (item_root.getVisibility() == View.VISIBLE) {
                    item_root.setVisibility(View.GONE);
                }
                if (message_ll.getVisibility() == View.VISIBLE) {
                    message_ll.setVisibility(View.GONE);
                }
                if (remind_linearlayout.getVisibility() == View.VISIBLE) {
                    remind_linearlayout.setVisibility(View.GONE);
                }
            }

            //设置标题轮播图
            String data3 = db.selectCache("Banner");
            if (data3 != null && !data3.equals("") && !data3.equals("null")) {
                try {
                    //解析并显示
                    JSONArray array = new JSONArray(data3);
                    final ArrayList<HomeTopBean> arrayList = new ArrayList<>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String pictureUrl = jsonObject.optString("pictureUrl");
                        String id = jsonObject.optString("id");
                        HomeTopBean homeTopBean = new HomeTopBean();
                        homeTopBean.setPictureUrl(pictureUrl);
                        homeTopBean.setId(id);
                        arrayList.add(homeTopBean);
                    }
                    if (arrayList.size() > 0) {
                        imageLoader.displayImage(arrayList.get(0).getPictureUrl(), banner_image, options, new ImageLoadingListener() {
                            @Override
                            public void onLoadingStarted(String s, View view) {
                                //开始加载的时候执行
                            }

                            @Override
                            public void onLoadingFailed(String s, View view, FailReason failReason) {
                                //加载失败的时候执行
                                banner_image.setImageResource(R.mipmap.bj);
                            }

                            @Override
                            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                                //加载成功的时候执行
                            }

                            @Override
                            public void onLoadingCancelled(String s, View view) {
                                //加载取消的时候执行
                                banner_image.setImageResource(R.mipmap.bj);
                            }
                        });
                    } else {
                        banner_image.setImageResource(R.mipmap.bj);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 登陆后随机推送内容
     *
     * @param id 内容ID
     */
    public void getNewNotification(final int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.Home_ToDay(id, 1)).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 200 || code == 204) {
                        JSONObject jsonObject = new JSONObject(bodys);
                        JSONArray items = jsonObject.getJSONArray("items");
                        JSONObject object = items.getJSONObject(0);
                        String title = object.optString("title");
                        String pictureUrl = object.optString("pictureUrl");
                        String shortDescription = object.optString("shortDescription");
                        String id = object.optString("id");
                        JSONObject jsonObject1 = new JSONObject(object.getString("category"));
                        String name = jsonObject1.getString("name");
                        Bundle bundle = new Bundle();
                        bundle.putString("title", title);
                        bundle.putString("pictureUrl", pictureUrl);
                        bundle.putString("shortDescription", shortDescription);
                        bundle.putString("id", id);
                        bundle.putString("name", name);
                        Message msg2 = new Message();
                        msg2.what = 5;
                        msg2.obj = bundle;
                        loginHandler.sendMessage(msg2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
